package com.ytd.common.util;

import android.text.TextUtils;

import androidx.annotation.NonNull;

/**
 * Your class notes
 *
 * @author gaoguanchao
 * @since 2023/10/23 0023
 */
public class AdbDebugUtil {
    public static CommandExecution.CommandResult start() {
        return CommandExecution.execCommand(Config.START_MONITOR, true);
    }

    public static CommandExecution.CommandResult stop() {
        return CommandExecution.execCommand(Config.STOP_MONITOR, true);
    }

    public static boolean check() {
        CommandExecution.CommandResult commandResult = CommandExecution.execCommand(Config.CHECK_MONITOR, true);
        return portIsValid(commandResult.successMsg);
    }

    private static boolean portIsValid(@NonNull String result) {
        try {
            return !TextUtils.isEmpty(result) && Integer.parseInt(result) == Config.PORT;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return false;
        }
    }


    public interface Config {
        int PORT = 5555;
        int EOF_PORT = -1;

        String SH = "sh";
        String SU = "su";
        String END_LINE = "\n";
        String EXIT = "exit";
        String TARGET = "service.adb.tcp.port";
        String GET = "getprop";
        String SET = "setprop";
        String SPACE = " ";

        String[] CHECK_MONITOR = new String[] {
            GET + SPACE + TARGET
        };

        String[] START_MONITOR = new String[] {
            SET + SPACE + TARGET + SPACE + PORT,
            "stop adbd",
            "start adbd",
        };

        String[] STOP_MONITOR = new String[] {
            SET + SPACE + TARGET + SPACE + EOF_PORT,
            "stop adbd",
            "start adbd",
        };
    }
}
